// CyTargetLinker,
// a Cytoscape plugin to extend biological networks with regulatory interaction
// Copyright 2011-2012 BiGCaT Bioinformatics
//
// This class was adapted from the PDF Forms Designer project
// Project Info:  http://pdfformsdesigne.sourceforge.net
//
//	  This library is free software; you can redistribute it and/or
//    modify it under the terms of the GNU General Public
//    License as published by the Free Software Foundation; either
//    version 2.1 of the License, or (at your option) any later version.
//
package org.pdf.forms.gui.properties.customcomponents.colorcombobox;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ComboBoxEditor;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.event.EventListenerList;

public class ColorComboBoxEditor implements ComboBoxEditor {
	final protected JLabel editor;

	protected EventListenerList listenerList = new EventListenerList();

	public ColorComboBoxEditor(Color initialColor) {
		editor = new JLabel();
		editor.setBackground(initialColor);
		editor.setOpaque(true);
		Color currentBackground = editor.getBackground();
		JComboBox colorComboBoxEdit = new JComboBox();
		Color color = colorComboBoxEdit.getBackground();
		if ((color != null) && (currentBackground != color)) {
			editor.setBackground(color);
			fireActionEvent(color);
		}
	}

	public void addActionListener(ActionListener l) {
		listenerList.add(ActionListener.class, l);
	}

	public Component getEditorComponent() {
		return editor;
	}

	public Object getItem() {
		return editor.getBackground();
	}

	public void removeActionListener(ActionListener l) {
		listenerList.remove(ActionListener.class, l);
	}

	public void selectAll() {
	}

	public void setItem(Object newValue) {
		if (newValue instanceof Color) {
			Color color = (Color) newValue;
			editor.setBackground(color);
		} else {
			try {
				Color color = Color.decode(newValue.toString());
				editor.setBackground(color);
			} catch (NumberFormatException e) {
			}
		}
	}

	protected void fireActionEvent(Color color) {
		Object listeners[] = listenerList.getListenerList();
		for (int i = listeners.length - 2; i >= 0; i -= 2) {
			if (listeners[i] == ActionListener.class) {
				ActionEvent actionEvent = new ActionEvent(editor, ActionEvent.ACTION_PERFORMED, color.toString());
				((ActionListener) listeners[i + 1]).actionPerformed(actionEvent);
			}
		}
	}
}


